<template>
  <div>
    <!-- 面包屑导航条 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button @click="addTypeInfo" type="primary" size="medium">添加分类</el-button>
    <el-table :data="categoryList" style="width: 100%">
      <el-table-column type="index"></el-table-column>
      <el-table-column label="分类名称">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" placeholder="请输入分类名称"></el-input>
        </template>
      </el-table-column>

      <el-table-column label="申请状态" prop="status">
        <template slot-scope="scope">
          <div style="display :flex;align-items:center;" @click="showActionImgAction(scope)">
            <el-image style="width: 50px; height:50px;margin-right:20px;" :src="scope.row.imgUrl"></el-image>
            <el-button size="small" type="primary">修改分类图片</el-button>
          </div>

          <!-- <el-image
            style="width: 50px; height:50px"
            :src="scope.row.imgUrl"
            :preview-src-list="[scope.row.imgUrl]"
          ></el-image>-->
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="createTime">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.active" @change="editSwitchType(scope,$event)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="所属分类">
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="handleCommand(scope,$event)">
            <span class="el-dropdown-link">
              {{scope.row.title}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="i" v-for="(item,i) in typeList" :key="i">{{item.name}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="confirmType(scope)">保存修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="修改分类图片" :visible.sync="editTypeImgBtn" width="40%">
      <el-upload
        style="display:flex;align-item:center; flex-direction: column;margin-top:1rem;"
        class="upload-demo"
        :data="params"
        :action="form.Url"
        :before-upload="dTbeforeUploadList"
        :on-success="dTuploadSuccessList"
        :file-list="fileList"
        limit="1"
        list-type="picture"
      >
        <el-button size="small" type="primary">上传分类图片</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editTypeImgBtn=false">取 消</el-button>
        <el-button type="primary" @click="editTypeImg">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加分类" :visible.sync="changDialogVisibleo" width="50%">
      <div style="display:flex;align-items:center;">
        <div style="margin-right:40px;flex-shrink: 0;">分类名称</div>
        <el-input v-model="formData.title" placeholder="请输入内容"></el-input>
      </div>
      <div style="display:flex;align-items:center;margin-top:20px;">
        <div style="margin-right:40px;">所属分类</div>
        <el-dropdown @command="handleCommandData">
          <span class="el-dropdown-link">
            {{title}}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="i" v-for="(item,i) in typeList" :key="i">{{item.name}}</el-dropdown-item>
            <!-- <el-dropdown-item command="b">狮子头</el-dropdown-item>
                <el-dropdown-item command="c">螺蛳粉</el-dropdown-item>
                <el-dropdown-item command="d">双皮奶</el-dropdown-item>
            <el-dropdown-item command="e">蚵仔煎</el-dropdown-item>-->
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <div style="display:flex;align-items:center;margin-top:20px;">
        <div style="margin-right:40px;">是否开启</div>
        <el-switch v-model="activeBtn" @change="addSwitchType"></el-switch>
      </div>

      <el-upload
        style="display:flex;align-item:center; flex-direction: column;margin-top:1rem;"
        class="upload-demo"
        :data="params"
        :action="form.Url"
        :on-remove="dThandleRemove"
        :before-upload="dTbeforeUpload"
        :on-success="dTuploadSuccess"
        list-type="picture"
      >
        <!-- list-type="picture"-->
        <el-button size="small" type="primary">上传分类图片</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changDialogVisibleo=false">取 消</el-button>
        <el-button type="primary" @click="addTypeConfirm">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoryList: [],
      typeList: [],
      changDialogVisibleo: false,
      formData: {
        title: "",
        image: "",
        id: "",
      },
      form: {
        token: "", //七牛token
        Url: "", //获取上传路径
        domain: "", //上传路径 二级
      },
      params: {
        token: "",
        key: "",
      },
      title: "请选择",
      activeBtn: true,
      paramsData: {
        token: "",
        key: "",
      },
      editTypeImgBtn: false,
      itemInfo: {},
      editImgUrl: "",
      fileList: [],
    };
  },
  created() {
    this.getCategoryList();
    this.getQnToken();
  },
  methods: {
    editTypeImg() {
      if (!this.editImgUrl) {
        this.$message.error("请上传分类图片!");
        return;
      }
      this.editTypeImgBtn = false;
      this.categoryList[this.itemInfo.$index].imgUrl = this.editImgUrl;
    },
    showActionImgAction(data) {
      this.itemInfo = data;
      console.log(data);
      this.fileList = [];
      this.editTypeImgBtn = true;
    },
    actionProductType(params) {
      this.changDialogVisibleo=false;
      this.$http.post("/manage/mall/addEditMallCategory", params).then((res) => {
        console.log(res);
        this.getEjTypeList();
        this.$message({
          message: "添加成功",
          type: "success",
        });

      });
    },
    dTuploadSuccessList(result) {
      console.log(result);
      if (result) {
        // 只要图片上传成功，都要 怼出这么一个对象：
        //  { pic: '图片的地址' }
        // 把怼出的对象，push 到this.addForm.pics 中
        let picUrl = this.form.domain + result.key;
        this.editImgUrl = picUrl;
        // this.categoryList[data.$index].imgUrl = picUrl;
      }
    },
    dTbeforeUploadList(file) {
      console.log("上传之前触发");
      if (file) {
        this.params.key = file.name;
        const isJPG = file.type === "image/jpeg" || file.type === "image/png";
        const isLt10M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
        }
      }
    },

    editSwitchType(data, index) {
      console.log(data, index);
    },
    addSwitchType(e) {
      //console.log(e);
      this.activeBtn = e;
    },
    addTypeInfo() {
      this.changDialogVisibleo = true;
    },
    handleCommandData(command) {
      console.log(this.typeList[command]);
      this.title = this.typeList[command].name;
      this.formData.id = this.typeList[command].id;
    },
    dTuploadSuccess(result) {
      // console.log(result)
      // 只要图片上传成功，都要 怼出这么一个对象：
      //  { pic: '图片的地址' }
      // 把怼出的对象，push 到this.addForm.pics 中
      let picUrl = this.form.domain + result.key;
      this.formData.image = picUrl;
      // console.log(this.addForm)
    },
    dThandleRemove(result) {
      // 根据要删除的图片的地址，找到 图片在 this.addForm.pics 数组中，
      // 所对应的 索引
      //const index = this.addForm.pics.findIndex(x => x.pic === result.response.data.tmp_path)
      // 根据索引。把 表单中记录的图片信息对象，删除
      this.formData.image = "";
      // console.log(this.addForm)
    },
    dTbeforeUpload(file) {
      console.log(file);
      this.params.key = file.name;
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
    },
    //单图预览
    async getQnToken() {
      const { data: res } = await this.$http.post(
        "/userFile/qiNiuUpload",
        {}
      );
      console.log(res.data.token);
      this.form.token = res.data.token;
      this.params.token = res.data.token;
      this.paramsData.token = res.data.token;
      this.form.domain = res.data.domain;
      this.form.Url = res.data.upload_url;
    },
    addTypeConfirm() {
      // formData: {
      //   title: "",
      //   image: "",
      //   id: ""
      // },
      if (!this.formData.title) {
        this.$message({
          message: "请输入分类名称",
          type: "warning",
        });
        return;
      }
      if (this.title == "请选择") {
        this.$message({
          message: "请选择所属分类",
          type: "warning",
        });
        return;
      }
      if (!this.formData.image) {
        this.$message({
          message: "请上传分类图片",
          type: "warning",
        });
        return;
      }
      let params = {
        disabled: this.activeBtn ? 0 : 1,
        imgUrl: this.formData.image,
        name: this.formData.title,
        father: this.formData.id,
        title:this.title
      };
      console.log(params);
      this.actionProductType(params);
    },
    confirmType(data) {
      console.log(data);
      let params = {
        disabled: data.row.active ? 0 : 1,
        imgUrl: data.row.imgUrl,
        name: data.row.name,
        father: data.row.father,
        title: data.row.title,
        id: data.row.id,
      };
      this.$http.post("/manage/mall/addEditMallCategory", params).then((res) => {
        console.log(res);
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getEjTypeList();
      });
    },
    handleCommand(data, index) {
      console.log(data, index);
      let title = this.typeList[index].name;
      this.categoryList[data.$index].title = title;
      this.categoryList[data.$index].father = this.typeList[index].id;
      // this.addForm.type = this.productTypeList[command].id;
      // this.$http.post("/manage/allm/addEditMallCategory", {}).then((res) => {
      //   this.buquanBtn = false;
      //   this.categoryList[data.$index].title = title;
      //   this.$message({
      //     message: "商品分类设置成功",
      //     type: "success",
      //   });
      // });
    },
    async getCategoryList() {
      await this.$http
        .post("/manage/mall/mallCategory", { queryType: 1 })
        .then((res) => {
          console.log(res);
          this.typeList = res.data.data;
        });
      await this.$http
        .post("/manage/mall/mallCategory", { queryType: 2 })
        .then((res) => {
          console.log(res);
          res.data.data.forEach((element) => {
            if (element.disabled == 0) {
              element.active = true;
            } else {
              element.active = false;
            }
            this.typeList.forEach((item) => {
              if (element.father == item.id) {
                element.title = item.name;
              }
            });
          });
          this.categoryList = res.data.data;
        });
    },
    getEjTypeList() {
      this.$http
        .post("/manage/mall/mallCategory", { queryType: 2 })
        .then((res) => {
          console.log(res);
          res.data.data.forEach((element) => {
            if (element.disabled == 0) {
              element.active = true;
            } else {
              element.active = false;
            }
            this.typeList.forEach((item) => {
              if (element.father == item.id) {
                element.title = item.name;
              }
            });
          });
          this.categoryList = res.data.data;
        });
    },
  },
};
</script>

<style lang="less" scoped>
.base-flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>
